import os
import re

import jenkins
from conf.conf_opertion import ConfOpertion

class JenkinsOpertion:
    def __init__(self):
        conf=ConfOpertion()
        self.jenkins_data={
            'url': conf.get_jenkins_value('url'),
            'username': conf.get_jenkins_value('username'),
            'password': conf.get_jenkins_value('password'),
            # 注意必须是整形
            'timeout': int(conf.get_jenkins_value('timeout'))
        }
        self.jenkins_server=jenkins.Jenkins(**self.jenkins_data)
        self.job_name=conf.get_jenkins_value('job_name')

    def get_job_number(self):
        """读取jenkins job构建号"""
        build_number = self.jenkins_server.get_job_info(self.job_name).get('lastBuild').get('number')
        return build_number

    def get_build_job_status(self):
        """读取构建完成的状态"""
        build_num = self.get_job_number()
        job_status = self.jenkins_server.get_build_info(self.job_name, build_num).get('result')
        return job_status

    def get_console_log(self):
        """获取控制台日志"""
        console_log = self.jenkins_server.get_build_console_output(self.job_name, self.get_job_number())
        return console_log

    def get_job_description(self):
        """返回job描述信息"""
        description = self.jenkins_server.get_job_info(self.job_name).get('description')
        url = self.jenkins_server.get_job_info(self.job_name).get('url')

        return description, url

    def get_build_report(self):
        """返回第n次构建的测试报告"""
        report = self.jenkins_server.get_build_test_report(self.job_name, self.get_job_number())
        return report

    def report_success_or_fail(self):

        # 拼接Allure报告标准路径
        # http://192.168.1.100:8080/job/ApiAutoTest/42/allure/
        # http://localhost:8080/job/ApiAutoTest/allure/

        report_url = f"{self.jenkins_data['url']}/job/{self.job_name}/{self.get_job_number()}/allure/"
        return report_url

if __name__ == '__main__':
    jo=JenkinsOpertion()
    print(jo.get_job_number())
    print(jo.report_success_or_fail())